package com.autonavi.yunda.yunji.common.thread;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author cizhong.wcs
 * @date 2022/6/21 14:23
 */
public class ThreadPoolMonitor {
    List<TraceableThreadPoolTaskExecutor> threadPoolTaskExecutorList;

    public ThreadPoolMonitor(List<TraceableThreadPoolTaskExecutor> threadPoolTaskExecutorList) {
        this.threadPoolTaskExecutorList = threadPoolTaskExecutorList;
    }

    public List<ThreadPoolInfo> getThreadInfo() {
        List<ThreadPoolInfo> infoList = new ArrayList<>();
        for (TraceableThreadPoolTaskExecutor threadPool : threadPoolTaskExecutorList) {
            ThreadPoolInfo info = new ThreadPoolInfo();
            info.setLabel(threadPool.getThreadNamePrefix().trim());
            //存活数量
            info.setActiveCount(threadPool.getActiveCount());
            //线程池基本大小
            info.setCorePoolSize(threadPool.getCorePoolSize());
            //最大数量
            info.setMaxPoolSize(threadPool.getMaxPoolSize());
            //当前线程池大小
            info.setPoolSize(threadPool.getPoolSize());
            //线程组名字
            ThreadGroup threadGroup = threadPool.getThreadGroup();
            info.setThreadGroupName(threadGroup != null ? threadGroup.getName() : "");
            ThreadPoolExecutor threadPoolExecutor = ((ThreadPoolTaskExecutor) threadPool).getThreadPoolExecutor();
            //队列剩余长度
            info.setQueueRemainingCapacity(threadPoolExecutor.getQueue().remainingCapacity());
            //队列使用长度
            info.setQueueSize(threadPoolExecutor.getQueue().size());
            //近期任务平均时间
            info.setAverageTaskTime(threadPool.getAverageTaskTime());
            //执行的总任务数量
            info.setTotalTasks(threadPool.getTotalTasks());
            infoList.add(info);
        }
        return infoList;
    }

}
